﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DFGK_WMS.Repository
{
    public class TRoutewayRepository : BaseRepository<TRouteway>, ITRoutewayRepository
    {
        public TRoutewayRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }
        /// <summary>
        /// 添加巷道信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTrout(TRoutewayDto obj, out string message)
        {
            try
            {
                message = "";
                //string code = "Routeway";
                //var aobj = Context.TRouteways.AsNoTracking().Where(x => x.Code.Contains(code)).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                //if (aobj != null)
                //{
                //    string pattern = @"\d+";
                //    MatchCollection matches = Regex.Matches(aobj.Code, pattern);
                //    string value = matches[matches.Count - 1].Value;
                //    int values = Convert.ToInt32(value);
                //    values++;
                //    obj.Code = code + values.ToString("D4");
                //}
                //else
                //{
                //    int i = 1;
                //    obj.Code = code + i.ToString("D4");
                //}

                var robj = Context.TRouteways.AsNoTracking().FirstOrDefault(x => x.Code == obj.Code);
                if (robj != null) 
                {
                    message = "编码已存在！";
                    return false;
                }
                //库房
                var wobj = Context.TWarehouses.Find(obj.WhId);
                if(wobj!=null && wobj.Status==1)
                {
                    obj.WhCode= wobj.Code;
                    obj.WhName= wobj.Name;
                }
                else
                {
                    message = "库房不存在或已被禁用！";
                    return false;
                }
                TRouteway trout = new TRouteway();
                trout = Mapper.Map<TRouteway>(obj);
                trout.CreateUserId = obj.CreateUserId ;
                trout.CreateUserName = obj.CreateUserName ;
                trout.CreateDate = DateTime.Now;
                Context.TRouteways.Add(trout);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除巷道信息
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelTrout(int uid)
        {
            try
            {
                var del = Context.TRouteways.Find(uid);
                if (del != null)
                {
                    Context.TRouteways.Remove(del);
                    return Context.SaveChanges() > 0;
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 根据id获取信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TRouteway GetTroutById(int id)
        {
            try
            {
                return Context.TRouteways.Find(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示巷道信息（弃用）
        /// </summary>
        /// <param name="xname"></param>
        /// <param name="kid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TRoutewayDto> GetTroutList(string xname,int kid,int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var alist = Context.TRouteways.AsQueryable();
                var blist = Context.TWarehouses.AsQueryable();
                if (!string.IsNullOrEmpty(xname))
                {
                    alist = alist.Where(c => c.Name.Contains(xname));
                }
                if (kid > 0)
                {
                    alist = alist.Where(c => c.WhId == kid);
                }
                var query = from A in alist
                            join B in blist
                            on A.WhId equals B.Id
                            select new TRoutewayDto
                            {
                                Id = A.Id,
                                Code = A.Code,
                                Name = A.Name,
                                WhCode = A.WhCode,
                                WhName = A.WhName,
                                Number = A.Number,
                                Status = A.Status,
                                Remark = A.Remark,
                                DisplayOrder = A.DisplayOrder,
                                CreateDate = A.CreateDate,
                                CreateUserId = A.CreateUserId,
                                CreateUserName = A.CreateUserName,
                                ModifyDate = A.ModifyDate,
                                ModifyUserId = A.ModifyUserId,
                                ModifyUserName = A.ModifyUserName,
                                KName = B.Name
                            };
                totalCount = query.Count();
                query = query.OrderBy(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                return query.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 显示巷道信息
        /// </summary>
        /// <param name="xname"></param>
        /// <param name="wid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TRouteway> GetTroutnList(string xname, int wid, int pageIndex, int pageSize, out int totalCount)
        {
            var rlist = Context.TRouteways.AsQueryable();

            //巷道名称
            if(!string.IsNullOrEmpty(xname))
            {
                rlist = rlist.Where(x => x.Name.Contains(xname));
            }
            //库房
            if(wid!=0)
            {
                rlist = rlist.Where(x => x.WhId == wid);
            }

            totalCount= rlist.Count();

            rlist = rlist.OrderBy(x=>x.DisplayOrder).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return rlist.ToList();
        }

        /// <summary>
        /// 获取库房(库房)信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TWarehouse> GetTwarehouseList()
        {
            try
            {
                return Context.TWarehouses.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool Upd(TRouteway obj)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 修改巷道信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTrout(TRoutewayDto obj,out string message)
        {
            try
            {
                message = "";
                var robj = Context.TRouteways.AsNoTracking().FirstOrDefault(x => x.Id != obj.Id && x.Code == obj.Code);
                if(robj!=null)
                {
                    message = "编码已存在！";
                    return false;
                }
                //库房
                var wobj = Context.TWarehouses.Find(obj.WhId);
                if (wobj != null && wobj.Status==1)
                {
                    obj.WhCode = wobj.Code;
                    obj.WhName = wobj.Name;
                }
                else
                {
                    message = "库房不存在或已被禁用！";
                    return false;
                }
                TRouteway trout = new TRouteway();
                trout = Mapper.Map<TRouteway>(obj);
                obj.ModifyUserId = obj.ModifyUserId;
                obj.ModifyUserName = obj.ModifyUserName;
                obj.ModifyDate = DateTime.Now;
                Context.TRouteways.Update(trout);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }

        IQueryable<TRouteway> IBaseRepository<TRouteway>.GetAll()
        {
            throw new NotImplementedException();
        }
    }
}
